﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Reflection;
using HIHS.BaseLib.Basics;
namespace HIHS.Form.Main
{
    public class HIHSConsole : ICustom
    {
        private bool console;


        private void log(string cmd)
        {
            if (HIHSApplication.log != null)
                System.Console.Write(HIHSApplication.log.Read());
        }
        private void quit(string cmd)
        {
            FreeConsole();
            System.Windows.Forms.Application.ApplicationExit -= Application_ApplicationExit;
            console = false;
        }
        private void FC(string cmd)
        {
            System.Windows.Forms.Application.OpenForms[0].Invoke(new Action (() => { 
            FunctionControl.FCMain fc = new FunctionControl.FCMain();
            fc.Show();
            }));
        }

        public void FunctionInvoke(System.Windows.Forms.Form mainFrom, BaseLib.FunctionEntity fe)
        {
            if (console)
                return;
            System.Windows.Forms.Application.ApplicationExit += Application_ApplicationExit;
            new System.Threading.Thread(() =>
            {
                console = true;
                AllocConsole();
                Type t = typeof(HIHSConsole);
                MethodInfo[] meths = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
                while (console)
                {
                    //System.Console.h
                    string intext = System.Console.ReadLine();
                    if (string.IsNullOrEmpty(intext))
                        continue;

                    intext = intext.Trim().ToUpper();
                    string cmd = intext;
                    string arg = "";
                    if (intext.IndexOf(' ') > 0)
                    {
                        cmd = intext.Substring(0, intext.IndexOf(' '));
                        arg = intext.Substring(intext.IndexOf(' '));
                    }
                    System.Reflection.MemberInfo info = meths.LastOrDefault(o => o.Name.ToUpper() == cmd);
                    if (info != null)
                        ((MethodInfo)info).Invoke(this, new object[] { arg });
                }
            }).Start();
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            quit("");
        }





        [DllImport("kernel32.dll")]
        private static extern Boolean AllocConsole();
        [DllImport("kernel32.dll")]
        private static extern Boolean FreeConsole();

        [DllImport("kernel32.dll")]
        private static extern int SetConsoleCtrlHandler(myfunc action, Boolean isAdd);

        [DllImport("kernel32.dll")]
        private static extern int AttachConsole(int Pid);

        private delegate Boolean myfunc(int dwtype);
    }
}
